import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  telephone: '',
  password: '',
  email: '',
  switch: 'open',
  tokenDialogVisible: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TELEPHONE: (state, telephone) => {
    state.telephone = telephone
  },
  SET_PASSWORD: (state, password) => {
    const Base64 = require('js-base64')
    state.password = Base64.decode(password)
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_TOKENDIALOG: (state, tokenDialogVisible) => {
    state.tokenDialogVisible = tokenDialogVisible
  },
  GET_SWITCH: (state, value) => {
    state.switch = value
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password }).then(response => {
        const { data } = response.data
        commit('GET_SWITCH', 'shut')
        commit('SET_TOKEN', data.auth.token)
        commit('SET_NAME', data.user_info.real_name)
        commit('SET_AVATAR', data.user_info.avatar)
        commit('SET_EMAIL', data.user_info.email)
        commit('SET_TELEPHONE', data.user_info.telephone)
        commit('SET_PASSWORD', password)
        setToken(data.auth.token)
        localStorage.setItem('email', data.user_info.email)
        Cookies.set('sign', { account: account.trim(), password: password })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
